/**
 * 데이터 송수신
 * 조건 분기처리
 */

package network;

import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.net.Socket;
import java.util.Iterator;
import java.util.Set;
import java.util.Vector;

import javax.swing.DefaultListModel;

public class MultiChatClientThread extends Thread {
	MultiChatClient mcc;
	Socket socket;
	boolean tFlag = true;
	ObjectOutputStream send;
	ObjectInputStream receive;
	DefaultListModel<String> model;

	public MultiChatClientThread(MultiChatClient mcc, Socket s) {
		this.mcc = mcc;
		this.socket = s;
	}

	public void run() {
		try {
			send = new ObjectOutputStream(socket.getOutputStream());
			receive = new ObjectInputStream(socket.getInputStream());

			SocketData sd;
			if ("login".equals(mcc.comm)) {
				sd = new SocketData("login", mcc.getUser(),
						"로그인 되었습니다.", null);
				send.writeObject(sd);
				
			}
			
			while (tFlag) {
				sd = (SocketData) receive.readObject();	
				mcc.dataSet(sd);
				if("userlist".equals(sd.getCommand())){
					listSet(sd);
				}
				//login을 전송한 후 서버는 userlist로 메시지를 재전송
//				if(sd.getCommand().equals("serverdown")){
//					tFlag = false;
//					send.writeObject(sd);
//					
//				}else if(sd.getCommand().equals("userlist")){
//					mcc.list.removeAll();
//					mcc.clientList = (Vector)sd.getObj();
//					mcc.list.setListData(mcc.clientList);
//					
//				}else if(sd.getCommand().equals("logout")){
//					if(sd.getUser().equals(mcc.userID.getText())){//내자신이 로그아웃
//						tFlag=false;
//						mcc.clientList.removeAllElements();
//						
//					}else{
//						mcc.clientList.removeElement(sd.getUser());
//					}
//					mcc.list.setListData(mcc.clientList);
//				}
			}
			
//			receive.close();send.close();
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
	
	public void sendMsg(SocketData sd){
		try {
			int index = mcc.comboBox.getSelectedIndex();
			if(index > 0){
				sd.setIndex(index);
			}
			send.writeObject(sd);
			send.flush();
			mcc.comboBox.setSelectedIndex(0);
		} catch (Exception e) {
			// TODO: handle exception
			e.printStackTrace();
		}
	}
	
	
	public void listSet(SocketData sd){

		mcc.list.removeAll();
		mcc.model.clear();//mcc의 리스트 초기화
		
		model = (DefaultListModel<String>) sd.getObj();
		
		for(int i = 0; i<model.size();i++){
			mcc.model.addElement(model.get(i));
		}
	}

}